package com.mf.morefun.ui.comment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.R;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.AliInfoBean;
import com.mf.morefun.bean.CommentBean;
import com.mf.morefun.bean.EventMessageBean;
import com.mf.morefun.bean.GrindingEarsBean;
import com.mf.morefun.bean.HomeWorkRecordBean;
import com.mf.morefun.bean.ListenOriginalBean;
import com.mf.morefun.bean.LocalListenBean;
import com.mf.morefun.bean.MfPicaudioRelListBean;
import com.mf.morefun.bean.MfTpComment;
import com.mf.morefun.bean.MfUserImgRecordListBean;
import com.mf.morefun.bean.MfimgListBean;
import com.mf.morefun.bean.PMUserBean;
import com.mf.morefun.bean.ReadRecordBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.bean.ShareBean;
import com.mf.morefun.bean.UserInfoBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.listener.ClassNumListen;
import com.mf.morefun.receiver.NetUtil;
import com.mf.morefun.requestbean.RequestAchievementBean;
import com.mf.morefun.requestbean.RequestCommentRecordBean;
import com.mf.morefun.requestbean.RequestGetCommentBean;
import com.mf.morefun.requestbean.RequestHomeWorkSaveBean;
import com.mf.morefun.requestbean.RequestPMBean;
import com.mf.morefun.requestbean.RequestReadRecordBean;
import com.mf.morefun.requestbean.RequestSendFlowerBean;
import com.mf.morefun.requestbean.RequestShareBean;
import com.mf.morefun.requestbean.RequestUserBean;
import com.mf.morefun.service.CommentRecordService;
import com.mf.morefun.service.HomeWorkOriginalService;
import com.mf.morefun.service.MusicCommentService;
import com.mf.morefun.ui.dohomework.HomeworkListActivity;
import com.mf.morefun.ui.dohomework.LiteraryCreationActivity;
import com.mf.morefun.ui.moreread.ListenRecordActivity;
import com.mf.morefun.ui.userinfo.LoginActivity;
import com.mf.morefun.util.DownloadUtils;
import com.mf.morefun.util.GetUserInfo;
import com.mf.morefun.util.IsLoginBean;
import com.mf.morefun.util.SendStarOrFlowerNet;
import com.mf.morefun.util.UploadUtil;
import com.mf.morefun.util.record.LameMp3Manager;
import com.mf.morefun.util.record.MediaPlayUtil;
import com.mf.morefun.util.record.MediaRecorderListener;
import com.mf.morefun.widget.NetErrorPop;
import com.mf.morefun.widget.RoundProcessDialog;
import com.mf.morefun.widget.TransformationCommitUtils;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.zhcx.zhcxlibrary.commenplayer.CommenPlayer;
import com.zhcx.zhcxlibrary.commenplayer.listener.IPlayerListener;
import com.zhcx.zhcxlibrary.commenplayer.listener.OnNetListener;
import com.zhcx.zhcxlibrary.commenplayer.ui.ControlLayout;
import com.zhcx.zhcxlibrary.utils.AppManager;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import tv.danmaku.ijk.media.player.IMediaPlayer;

import static android.support.constraint.Constraints.TAG;

public class CommentActivity extends BaseBusActivity implements MediaRecorderListener {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_flower)
    TextView tvFlower;
    @BindView(R.id.ll_sendflower)
    LinearLayout llSendflower;
    @BindView(R.id.v_voice)
    View vVoice;
    @BindView(R.id.iv_voicetype)
    ImageView ivVoicetype;
    @BindView(R.id.iv_record_show)
    ImageView ivRecordShow;
    @BindView(R.id.voice_recond_play)
    ImageView voiceRecondPlay;
    @BindView(R.id.iv_luyin)
    ImageView ivLuyin;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.rl_voice)
    RelativeLayout rlVoice;
    @BindView(R.id.iv_text)
    ImageView ivText;
    @BindView(R.id.tv_text)
    TextView tvText;
    @BindView(R.id.ll_text)
    LinearLayout llText;
    @BindView(R.id.iv_voicecomment)
    ImageView ivVoicecomment;
    @BindView(R.id.tv_voicecomment)
    TextView tvVoicecomment;
    @BindView(R.id.ll_voicecomment)
    LinearLayout llVoicecomment;
    @BindView(R.id.iv_listen)
    ImageView ivListen;
    @BindView(R.id.tv_listen)
    TextView tvListen;
    @BindView(R.id.voice_recond_type)
    ImageView voiceRecondType;
    @BindView(R.id.ll_listen)
    LinearLayout llListen;
    @BindView(R.id.iv_re)
    ImageView ivRe;
    @BindView(R.id.tv_re)
    TextView tvRe;
    @BindView(R.id.ll_re)
    LinearLayout llRe;
    @BindView(R.id.ll_comment)
    LinearLayout llComment;
    @BindView(R.id.ll_left)
    LinearLayout llLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_fundamental)
    ImageView ivFundamental;
    @BindView(R.id.ll_listen_fundamental)
    LinearLayout llListenFundamental;
    @BindView(R.id.iv_listen_record)
    ImageView ivListenRecord;
    @BindView(R.id.ll_listen_record)
    LinearLayout llListenRecord;
    @BindView(R.id.ll_share)
    LinearLayout llShare;
    @BindView(R.id.player)
    CommenPlayer player;
    @BindView(R.id.vp_info)
    ViewPager vpInfo;
    @BindView(R.id.pb_speed)
    ProgressBar pbSpeed;
    @BindView(R.id.rl_img)
    RelativeLayout rlImg;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    @BindView(R.id.ly_content)
    LinearLayout lyContent;
    private String bookId = "";
    private String mfRecordId = "";
    private RoundProcessDialog dialog;
    private SPUtils mSPUtils;
    private List<View> viewContains = new ArrayList<View>();//viewpager容器
    private int currentPosition = 0;
    private MyPagerAdapter myPagerAdapter;
    private int totalPage = 0;
    private CommentRecordService mCommentRecordService = null;
    private String type = "";
    private List<MfUserImgRecordListBean> mRecordList = new ArrayList<>();//录音的集合
    private HomeWorkOriginalService mHomeWorkOriginalService = null;
    private List<LocalListenBean> mLocalViewList = new ArrayList<>();//重新创建一个集合来存排序好的集合
    private String bookName = "";//书名
    private DbManager manager;
    private String contextType = "1";
    private String mediaType = "1";
    private String contextId = "";
    private boolean ignoreNet;
    private String recordName = "";
    private AnimationDrawable animationDrawablePlay;
    private AnimationDrawable animationDrawableType;
    private String mfComment = "";
    private MfTpComment mfTpComment = null;
    private MusicCommentService musicCommentService;
    private SendStarOrFlowerNet mSendStartOrFlowerNet;
    private String userId = "";
    PowerManager powerManager = null;
    PowerManager.WakeLock wakeLock = null;

    private  String StudentCountryId = "";

    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_comment;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        //清空缓存
        File file = new File(getBasePath());

        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f: files)
        {
                f.delete();
        }

        mSPUtils = new SPUtils(getApplicationContext());

        powerManager = (PowerManager)this.getSystemService(this.POWER_SERVICE);
        wakeLock = this.powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock2");
        if (!IsLoginBean.isNo(false)) {
            GetUserInfo.initLogin(mSPUtils.getString(Configuration.USERPHONE), mSPUtils.getString(Configuration.USERPASSWORD));
        }
        animationDrawablePlay = (AnimationDrawable) voiceRecondPlay
                .getBackground();
        animationDrawableType = (AnimationDrawable) voiceRecondType
                .getBackground();
        EventBus.getDefault().register(this);
        manager = x.getDb(MoreFunApplication.daoConfig);
        userId = getIntent().getStringExtra(Configuration.USERID);

        mfComment = getIntent().getStringExtra("MFCOMMENT");
        if (!StringUtils.isEmpty(mfComment)) {
            mfTpComment = JSON.parseObject(mfComment, MfTpComment.class);
            if (null != mfTpComment) {
                bookId = mfTpComment.getBook().getId();
            }
        }

        if (IsLoginBean.isNo(true)) {


            if (StringUtils.isEmpty(MoreFunApplication.loginBean.getResult().getUserType())) {//老师才能看到语音点评按钮
                llVoicecomment.setVisibility(View.GONE);
            } else {
                if (MoreFunApplication.loginBean.getResult().getUserType().equals("1")) {

                    tvName.setText(MoreFunApplication.loginBean.getResult().getName());

                    showCicleImg(MoreFunApplication.loginBean.getResult().getHeadPortrait());

                    llVoicecomment.setVisibility(View.GONE);

                    tvFlower.setEnabled(false);

                    llSendflower.setEnabled(false);

                    llRe.setVisibility(View.VISIBLE);

                    tvFlower.setText(MoreFunApplication.loginBean.getResult().getUserFinance().getFlows() + "");

                } else if (MoreFunApplication.loginBean.getResult().getUserType().equals("2")) {

                    String student = getIntent().getStringExtra("STUDENT");

                    if (!StringUtils.isEmpty(student)) {
                        initGetUser(student);
                    }

                    llVoicecomment.setVisibility(View.VISIBLE);
                    llSendflower.setEnabled(true);
                    tvFlower.setText("送花");
                    llRe.setVisibility(View.GONE);
                }else{

                    String student = getIntent().getStringExtra("STUDENT");

                    if (!StringUtils.isEmpty(student)) {
                        initGetUser(student);
                    }

                    llVoicecomment.setVisibility(View.VISIBLE);
                    llSendflower.setEnabled(true);
                    tvFlower.setText("送花");
                    llRe.setVisibility(View.GONE);
                }
            }
        }
        dialog = new RoundProcessDialog(CommentActivity.this, "");
        bookId = getIntent().getStringExtra("BOOKID");
        type = getIntent().getStringExtra("TYPE");
        mfRecordId = getIntent().getStringExtra("MFRECORDID");//作业id
        if (StringUtils.isEmpty(getIntent().getStringExtra("BOOKNAME"))) {
            bookName = "" + System.currentTimeMillis();
        } else {
            bookName = getIntent().getStringExtra("BOOKNAME") + "original";
        }



        if (type.equals("0")) {//作品
            llSendflower.setEnabled(false);
            rlImg.setVisibility(View.VISIBLE);
            player.setVisibility(View.GONE);
            contextType = "1";
            if (!StringUtils.isEmpty(bookId)) {
                ivFundamental.setImageResource(R.mipmap.tingyuanyin);
                if (mSPUtils.getBoolean(Configuration.USERSHARE, false)){
                    ivListenRecord.setImageResource(R.mipmap.tingluyin);
                }else {
                    ivListenRecord.setImageResource(R.mipmap.tingyuanyin);
                }
                initGetRead();
            }
            llText.setEnabled(false);
            ivText.setImageResource(R.mipmap.wenzi_gray);
            llVoicecomment.setEnabled(false);
            ivVoicecomment.setImageResource(R.mipmap.yuyin_gray);
            llListen.setEnabled(false);
            ivListen.setImageResource(R.mipmap.shouting_gray);
            llRe.setVisibility(View.GONE);
            mediaType = "1";
        } else {//作业
            llSendflower.setEnabled(true);
            llText.setEnabled(true);
            llVoicecomment.setEnabled(true);
            llListen.setEnabled(true);
            contextType = "2";
            if (!StringUtils.isEmpty(getIntent().getStringExtra("ISVIDEO"))) {//视频
                ivFundamental.setImageResource(R.mipmap.tingyuanyin);
                ivListenRecord.setImageResource(R.mipmap.tingyuanyin);
                if (null != mfTpComment) {
                    if (null != mfTpComment.getBook()) {
                        tvTitle.setText(mfTpComment.getBook().getName());
                    } else {
                        tvTitle.setText("");
                    }
                } else {
                    tvTitle.setText("");
                }
                rlImg.setVisibility(View.GONE);
                player.setVisibility(View.VISIBLE);
                //就去播放就行了
                mediaType = "2";
                llListenFundamental.setEnabled(false);
                llListenRecord.setEnabled(false);
                llListenFundamental.setBackgroundResource(R.drawable.gray_shapes);
                llListenRecord.setBackgroundResource(R.drawable.gray_shapes);
                contextId = getIntent().getStringExtra("MFRECORDID");
                initGetComment("2", contextId, "");
                if (!StringUtils.isEmpty(getIntent().getStringExtra("ISVIDEO"))) {
                    initPlayer();
                    player.play(getIntent().getStringExtra("ISVIDEO"));
                }
            } else {//图片
                if (!StringUtils.isEmpty(bookId) && !StringUtils.isEmpty(mfRecordId)) {
                    ivFundamental.setImageResource(R.mipmap.tingyuanyin);
                    if (mSPUtils.getBoolean(Configuration.USERSHARE, false)){
                        ivListenRecord.setImageResource(R.mipmap.tingyuanyin);
                    }else {
                        ivListenRecord.setImageResource(R.mipmap.tingluyin);
                    }
                    rlImg.setVisibility(View.VISIBLE);
                    player.setVisibility(View.GONE);
                    mediaType = "1";
                    llListenRecord.setEnabled(true);
                    llListenFundamental.setEnabled(false);
                    llListenFundamental.setBackgroundResource(R.drawable.gray_shapes);
                    llListenRecord.setBackgroundResource(R.drawable.blue_shapes);
                    initGetHomeWorkRead();
                }
            }
        }
        //判断bookid为空就用记录id
        if (StringUtils.isEmpty(bookId)) {
            recordName = mfRecordId;
        } else {
            recordName = bookId;
        }
        mSPUtils.putString(Configuration.SCORE, 20 + "");
        llRe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //给个时间判断  是否已经过期
                if (!getIntent().getBooleanExtra(Configuration.HOMEWORK, false)){
                    ToastUtils.show(getApplicationContext(), "作业已过期，不能重做!", 100);
                    return;
                }
                llText.setBackgroundResource(R.mipmap.noselect);
                llVoicecomment.setBackgroundResource(R.mipmap.noselect);
                llListen.setBackgroundResource(R.mipmap.noselect);
                llRe.setBackgroundResource(R.mipmap.mineselected);
                tvText.setTextColor(0xff666666);
                tvVoicecomment.setTextColor(0xff666666);
                tvListen.setTextColor(0xff666666);
                tvRe.setTextColor(getResources().getColor(R.color.white));
                ivText.setImageResource(R.mipmap.homeworktext);
                ivVoicecomment.setImageResource(R.mipmap.homeworkvoice);
                ivListen.setImageResource(R.mipmap.homeworklisten);
                ivRe.setImageResource(R.mipmap.homeworkreselect);
                voiceRecondType.setVisibility(View.INVISIBLE);
                if (null != animationDrawableType) {
                    animationDrawableType.stop();
                }
                stopPlay();
                stopRecord();
                if (null != mCommentRecordService && null != mCommentRecordService.player && mCommentRecordService.player.isPlaying()) {
                    mCommentRecordService.pause();
                }
                if (null != mHomeWorkOriginalService && null != mHomeWorkOriginalService.player && mHomeWorkOriginalService.player.isPlaying()) {
                    mHomeWorkOriginalService.pause();
                }
                if (null != player){
                    player.pause();
                }
                Intent mIntent = null;
                if (!StringUtils.isEmpty(getIntent().getStringExtra("ISVIDEO"))) {
                    mIntent = new Intent(CommentActivity.this, LiteraryCreationActivity.class);
                    mIntent.putExtra(Configuration.USERID, userId);
                    mIntent.putExtra("TITLE", getIntent().getStringExtra("TITLE"));
                    mIntent.putExtra("DESCRIPTION", getIntent().getStringExtra("DESCRIPTION"));
                    mIntent.putExtra("TPBUS", getIntent().getStringExtra("TPBUS"));
                    mIntent.putExtra("TPDETAILID", getIntent().getStringExtra("TPDETAILID"));
                    mIntent.putExtra("TP", getIntent().getStringExtra("TP"));
                    mIntent.putExtra("CONTEXTID", contextId);
                    mIntent.putExtra("CONTEXTTYPE", contextType);
                    mIntent.putExtra("MEDIATYPE", mediaType);
                    mIntent.putExtra("CLASSID", getIntent().getStringExtra("CLASSID"));
                    mIntent.putExtra(Configuration.USERID, userId);
                    startActivityForResult(mIntent, 0);
                }else {
                    mIntent = new Intent(CommentActivity.this, ListenRecordActivity.class);
                    mIntent.putExtra("BOOKID", bookId);
                    mIntent.putExtra("TYPE", "2");
                    mIntent.putExtra("BOOKNAME", bookName.replace("original", ""));
                    mIntent.putExtra("TITLE", getIntent().getStringExtra("TITLE"));
                    mIntent.putExtra("DESCRIPTION", getIntent().getStringExtra("DESCRIPTION"));
                    mIntent.putExtra("TPBUS", getIntent().getStringExtra("TPBUS"));
                    mIntent.putExtra("TPDETAILID", getIntent().getStringExtra("TPDETAILID"));
                    mIntent.putExtra("TP", getIntent().getStringExtra("TP"));
                    mIntent.putExtra("CONTEXTID", contextId);
                    mIntent.putExtra("CONTEXTTYPE", contextType);
                    mIntent.putExtra("MEDIATYPE", mediaType);
                    mIntent.putExtra("CLASSID", getIntent().getStringExtra("CLASSID"));
                    mIntent.putExtra(Configuration.USERID, userId);
                    startActivityForResult(mIntent, 1);
                }
            }
        });
    }


    private void initGetUser(String userId) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.USERINFO);
        RequestUserBean userBean = new RequestUserBean();
        userBean.setId(userId);
        params.setBodyContent(JSON.toJSONString(userBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d(result);
                if (!StringUtils.isEmpty(result)){
                    ResultBean mResult = JSON.parseObject(result, ResultBean.class);
                    if (mResult.getErrorCode() == 0){
                        if (!StringUtils.isEmpty(mResult.getResult())){

                            UserInfoBean user = JSON.parseObject(mResult.getResult(), UserInfoBean.class);

                            tvName.setText(user.getName());

                            showCicleImg(user.getHeadPortrait());

                            if (user.getCountry() != null) {

                                StudentCountryId = user.getCountry().getId();
                            }
                            else
                            {
                                StudentCountryId="0";
                            }

                            initGetAliInfo();


                        }
                    }else {
                        ToastUtils.show(getApplicationContext(), mResult.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private void initGetAliInfo() {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.GETALIINFOV2);

        /*params.setBodyContent("{\n" +
                " \n" +
                "}");
        */

        PMUserBean.CountryBean countrybean = new PMUserBean.CountryBean();
        countrybean.setId( StudentCountryId );
        params.setBodyContent(JSON.toJSONString(countrybean));

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    AliInfoBean aliInfoBean = JSON.parseObject(result, AliInfoBean.class);
                    if (aliInfoBean.getStatusCode() == 200) {
                        mSPUtils.putString(Configuration.ACCESSKEYID, aliInfoBean.getAccessKeyId());
                        mSPUtils.putString(Configuration.ACCESSKEYSECRET, aliInfoBean.getAccessKeySecret());
                        mSPUtils.putString(Configuration.SECURITYTOKEN, aliInfoBean.getSecurityToken());

                        mSPUtils.putString(Configuration.ENDPOINT, aliInfoBean.getEndPoint());
                        mSPUtils.putString(Configuration.BUCKETNAME, aliInfoBean.getBucketName());
                        mSPUtils.putString(Configuration.BUCKETDOMAIN, aliInfoBean.getBucketDomain());

                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void initGetComment(String type, String tpRecord, String workId) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.GETCOMMENT);
        RequestGetCommentBean requestGetCommentBean = new RequestGetCommentBean();
        requestGetCommentBean.setType(type);
        RequestGetCommentBean.WorkBean workBean = new RequestGetCommentBean.WorkBean();
        workBean.setId(workId);
        requestGetCommentBean.setWork(workBean);
        RequestGetCommentBean.TpRecordBean tpRecordBean = new RequestGetCommentBean.TpRecordBean();
        tpRecordBean.setId(tpRecord);
        requestGetCommentBean.setTpRecord(tpRecordBean);
        params.setBodyContent(JSON.toJSONString(requestGetCommentBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)){
                    ResultBean mResult = JSON.parseObject(result, ResultBean.class);
                    if (mResult.getErrorCode() == 0){
                        if (!StringUtils.isEmpty(mResult.getResult())){
                            CommentBean mComment = JSON.parseObject(mResult.getResult(), CommentBean.class);
                            if (null != mComment){
                                if (null != mComment.getCommentText()){
                                    if (null != mfTpComment){
                                        mfTpComment.setTeacherTextComment(mComment.getCommentText().getTeacherTextComment());
                                        mfTpComment.setUserCommentStar(mComment.getCommentText().getUserCommentStar());
                                    }else {
                                        mfTpComment = new MfTpComment();
                                        mfTpComment.setTeacherTextComment(mComment.getCommentText().getTeacherTextComment());
                                        mfTpComment.setUserCommentStar(mComment.getCommentText().getUserCommentStar());
                                    }
                                }
                                if (null != mComment.getCommentVoice()){
                                    if (null != mfTpComment){
                                        mfTpComment.setTeacherVoiceComment(mComment.getCommentVoice().getTeacherVoiceComment());
                                        mfTpComment.setUserCommentStar(mComment.getCommentVoice().getUserCommentStar());
                                    }else {
                                        mfTpComment = new MfTpComment();
                                        mfTpComment.setTeacherVoiceComment(mComment.getCommentVoice().getTeacherVoiceComment());
                                        mfTpComment.setUserCommentStar(mComment.getCommentVoice().getUserCommentStar());
                                    }
                                }
                                if (null != mComment.getReword()){
                                    tvFlower.setText(mComment.getReword().getRewardNumber() + "");
                                }else {
                                    tvFlower.setText("0");
                                }
                            }else {
                                tvFlower.setText("0");
                            }
                        }
                    }else {
                        ToastUtils.show(getApplicationContext(), mResult.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            if (requestCode == 0){
                if (!StringUtils.isEmpty(data.getStringExtra("ISVIDEO"))){
                    if (null != player) {
                        player.onDestroy();
                    }
                    initPlayer();
                    player.setUrl(data.getStringExtra("ISVIDEO"));
                }
            }else {
                mfRecordId = data.getStringExtra("MFRECORDID");
                initGetHomeWorkRead();
            }
        }
    }

    private void initPlayer() {
        player.setLive(false);
        player.setOnNetListener(new OnNetListener() {
            @Override
            public void onIgnoreMobileNet() {
                ignoreNet = true;
            }
        }).setOnPlayerListener(new IPlayerListener() {
            @Override
            public void onLoading() {
                player.getControl().setState(ControlLayout.STATE_LOADING);
            }

            @Override
            public void onCompletion(IMediaPlayer mp) {
                player.getControl().setState(ControlLayout.STATE_COMPLETION);
            }

            @Override
            public void onPrepared(IMediaPlayer mp) {
                //代表移动网
                if (!ignoreNet && NetUtil.getNetWorkState(CommentActivity.this) == 0) {
                    player.pause();
                    player.getControl().setState(ControlLayout.STATE_MOBILE_NET);
                } else {
                    player.getControl().setState(ControlLayout.STATE_PREPARED);
                }
            }

            @Override
            public boolean onError(IMediaPlayer mp, int what, int extra) {
                player.getControl().setState(ControlLayout.STATE_ERROR);
                return false;
            }

            @Override
            public boolean onInfo(IMediaPlayer mp, int what, int extra) {
                return false;
            }

            @Override
            public void onVideoSizeChanged(IMediaPlayer mp, int width, int height, int sarNum, int sarDen) {

            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (player != null) {
                player.onResume();
            }
            if (null != wakeLock){
                wakeLock.acquire();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        if (player != null) {
            player.onPause();
        }
        super.onPause();
        try {
            isCanPlay = false;
            if (null != mCommentRecordService && null != mCommentRecordService.player && mCommentRecordService.player.isPlaying()) {//把之前的销毁
                mCommentRecordService.stop();
            }
            if (null != mHomeWorkOriginalService && null != mHomeWorkOriginalService.player && mHomeWorkOriginalService.player.isPlaying()) {
                mHomeWorkOriginalService.pause();
            }
            if (null != musicCommentService && null != musicCommentService.player && musicCommentService.player.isPlaying()){
                musicCommentService.pause();
            }
            llListenFundamental.setBackgroundResource(R.drawable.blue_shapes);
            llListenFundamental.setEnabled(true);
            ivFundamental.setImageResource(R.mipmap.tingyuanyin);
            llListenRecord.setBackgroundResource(R.drawable.blue_shapes);
            llListenRecord.setEnabled(true);
            ivListenRecord.setImageResource(R.mipmap.tingyuanyin);
            if (null != wakeLock){
                wakeLock.release();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onConfigurationChanged(android.content.res.Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        ViewGroup.LayoutParams lp = player.getLayoutParams();
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        if (newConfig.orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE) {
            lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
            player.setLayoutParams(lp);
        } else {
            lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
            player.setLayoutParams(lp);
        }
        if (player != null) {
            player.onConfigurationChanged(newConfig);
        }
    }

    @Override
    public void onBackPressed() {
        if (player != null && player.onBackPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void finish() {
        if (player != null) {
            player.onDestroy();
        }
        super.finish();
        if (null != dialog && dialog.isShow()) {
            dialog.cancel();
        }
    }

    private void initGetHomeWorkRead() {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.HOMEWORKRECORD);
        RequestCommentRecordBean requestReadRecordBean = new RequestCommentRecordBean();
        requestReadRecordBean.setType("2");
        RequestCommentRecordBean.BookBean bookBean = new RequestCommentRecordBean.BookBean();
        bookBean.setId(bookId);
        RequestCommentRecordBean.UserBean userBean = new RequestCommentRecordBean.UserBean();
        userBean.setId(userId);
        RequestCommentRecordBean.MftpRecord tpDetailBean = new RequestCommentRecordBean.MftpRecord();
        tpDetailBean.setId(mfRecordId);
        requestReadRecordBean.setBook(bookBean);
        requestReadRecordBean.setUser(userBean);
        requestReadRecordBean.setMftpRecord(tpDetailBean);
        params.setBodyContent(JSON.toJSONString(requestReadRecordBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                mRecordList.clear();
                if (!StringUtils.isEmpty(result)) {
                    HomeWorkRecordBean readRecordBean = JSON.parseObject(result, HomeWorkRecordBean.class);
                    if (readRecordBean.getErrorCode() == 0) {
                        if (null != readRecordBean.getResult().getBook()) {
                            tvTitle.setText(readRecordBean.getResult().getBook().getName());
                        }
                        if (null != readRecordBean.getResult().getMftpRecord()){
                            contextId = readRecordBean.getResult().getMftpRecord().getId();
                            initGetComment("2", contextId, "");
                        }
                        if (!StringUtils.isEmpty(readRecordBean.getResult().getMfUserImgRecordList())) {
                            List<MfUserImgRecordListBean> mfUserImgRecordListBeanList = JSON.parseArray(readRecordBean.getResult().getMfUserImgRecordList(), MfUserImgRecordListBean.class);
                            mRecordList.addAll(mfUserImgRecordListBeanList);
                            showViewPager(mRecordList, null);
                        } else {
                            llListenFundamental.setBackgroundResource(R.drawable.blue_shapes);
                            llListenFundamental.setEnabled(true);
                            ivListenRecord.setImageResource(R.mipmap.tingyuanyin);
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), readRecordBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void initGetRead() {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.COMMENTREADRECORD);
        RequestReadRecordBean requestReadRecordBean = new RequestReadRecordBean();
        requestReadRecordBean.setType("1");
        RequestReadRecordBean.BookBean bookBean = new RequestReadRecordBean.BookBean();
        bookBean.setId(bookId);
        RequestReadRecordBean.UserBean userBean = new RequestReadRecordBean.UserBean();
        userBean.setId(userId);
        requestReadRecordBean.setBook(bookBean);
        requestReadRecordBean.setUser(userBean);
        params.setBodyContent(JSON.toJSONString(requestReadRecordBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                mRecordList.clear();
                if (!StringUtils.isEmpty(result)) {
                    ReadRecordBean readRecordBean = JSON.parseObject(result, ReadRecordBean.class);
                    if (readRecordBean.getErrorCode() == 0) {
                        if (null != readRecordBean.getResult().getBook()) {
                            tvTitle.setText(readRecordBean.getResult().getBook().getName());
                        }
                        contextId = readRecordBean.getResult().getMfWork().getId();
                        initGetComment("1", "", contextId);
                        if (!StringUtils.isEmpty(readRecordBean.getResult().getMfUserImgRecordList())) {
                            List<MfUserImgRecordListBean> mfUserImgRecordListBeanList = JSON.parseArray(readRecordBean.getResult().getMfUserImgRecordList(), MfUserImgRecordListBean.class);
                            mRecordList.addAll(mfUserImgRecordListBeanList);
                            showViewPager(mRecordList, null);
                        } else {
                            llListenFundamental.setBackgroundResource(R.drawable.blue_shapes);
                            llListenFundamental.setEnabled(true);
                            ivListenRecord.setImageResource(R.mipmap.tingyuanyin);
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), readRecordBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mCommentRecordService) {
            mCommentRecordService.stop();
        }
        if (null != mHomeWorkOriginalService) {
            mHomeWorkOriginalService.stop();
        }
        stopPlay();
        stopRecord();
        MoreFunApplication.isOut = true;//退出
        EventBus.getDefault().unregister(this);
        if (null != mSendStartOrFlowerNet){
            mSendStartOrFlowerNet.stopAnim();
        }
    }
    boolean isCanPlay = true;
    //接受CommentRecordService发过来的消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMusicMessage(EventMessageBean message) {
        if (message.getType() == 0) {//播放完成发过来的消息
            if (isRecording) {
                nextPlay();
            } else {
                isCanPlay = false;
                vpInfo.setCurrentItem(0);
                ivFundamental.setImageResource(R.mipmap.tingyuanyin);
                llListenFundamental.setEnabled(true);
                llListenFundamental.setBackgroundResource(R.drawable.blue_shapes);
                ivListenRecord.setImageResource(R.mipmap.tingyuanyin);
                llListenRecord.setEnabled(true);
                llListenRecord.setBackgroundResource(R.drawable.blue_shapes);
            }
        } else if (message.getType() == 1) {//播放失败发过来的消息
            if (isRecording) {
                nextPlay();
            } else {
                ivFundamental.setImageResource(R.mipmap.tingyuanyin);
                llListenFundamental.setEnabled(true);
                llListenFundamental.setBackgroundResource(R.drawable.blue_shapes);
                ivListenRecord.setImageResource(R.mipmap.tingyuanyin);
                llListenRecord.setEnabled(true);
                llListenRecord.setBackgroundResource(R.drawable.blue_shapes);
                ToastUtils.show(getApplicationContext(), "音乐文件加载失败", 100);
            }
        } else if (message.getType() == 101111) {

            //String host = Configuration.OOSROOT;// "http://morefunreadingproduct.oss-cn-shanghai.aliyuncs.com/";
            String host =  mSPUtils.getString(Configuration.BUCKETDOMAIN);

            teacherVoiceComment = host + message.getFileName();

            mSPUtils.putString(Configuration.TEACHERVOICECOMMENT, teacherVoiceComment);

            initSaveComment();
            //开始提交
        } else if (message.getType() == 102) {
            ToastUtils.show(getApplicationContext(), "上传失败", 100);
        } else if (message.getType() == 11) {
            voiceRecondType.setVisibility(View.INVISIBLE);
            if (null != animationDrawableType) {
                animationDrawableType.stop();
            }
        } else if (message.getType() == 13) {
            voiceRecondType.setVisibility(View.INVISIBLE);
            if (null != animationDrawableType) {
                animationDrawableType.stop();
            }
        } else {
            if (null != mHomeWorkOriginalService && null != mHomeWorkOriginalService.player && mHomeWorkOriginalService.player.isPlaying()) {
                //DateUtils.getSecond(formatTime(mHomeWorkOriginalService.player.getCurrentPosition()));
                long second = mHomeWorkOriginalService.player.getCurrentPosition();
                int position = currentPosition;
                //获得比例
                if (null != mLocalViewList && mLocalViewList.size() > 0) {
                    for (int i = 0; i < mLocalViewList.size(); i++) {
                        if (i == 0) {
                            if (second > 0 && second < (int) (mLocalViewList.get(i).getVodStart() * 1000)) {
                                currentPosition = 0;
                            }
                        } else if (second >= (int) (mLocalViewList.get(i - 1).getVodStart() * 1000) && second < (int) (mLocalViewList.get(i).getVodStart() * 1000)) {
                            currentPosition = i;
                        }
                    }
                }
                if (position != currentPosition) {
                    vpInfo.setCurrentItem(currentPosition);
                }
            }
        }
    }

    private String formatTime(long time) {
        return formatTime("mm:ss", time);
    }

    private String formatTime(String pattern, long milli) {
        int m = (int) (milli / DateUtils.MINUTE_IN_MILLIS);
        int s = (int) ((milli / DateUtils.SECOND_IN_MILLIS) % 60);
        String mm = String.format(Locale.getDefault(), "%02d", m);
        String ss = String.format(Locale.getDefault(), "%02d", s);
        return pattern.replace("mm", mm).replace("ss", ss);
    }


    private void nextPlay() {
        if (currentPosition < (totalPage - 1)) {
            currentPosition++;
            vpInfo.setCurrentItem(currentPosition);
        } else {
            //然后变成可以点击播放的样子
            llListenFundamental.setEnabled(true);
            llListenFundamental.setBackgroundResource(R.drawable.blue_shapes);
            ivListenRecord.setImageResource(R.mipmap.tingyuanyin);
            isCanPlay = false;
            vpInfo.setCurrentItem(0);
        }
    }

    private void showViewPager(List<MfUserImgRecordListBean> mfUserImgRecordListBeanList, List<LocalListenBean> mLocalList) {
        vpInfo.removeAllViews();
        viewContains.clear();
        setPagerAdapter();
        setPagerListener();
        if (null != mfUserImgRecordListBeanList && mfUserImgRecordListBeanList.size() > 0) {
            if (currentPosition >= mfUserImgRecordListBeanList.size()){
                currentPosition = 0;
            }
            isRecording = true;
            llListenFundamental.setEnabled(false);
            llListenFundamental.setBackgroundResource(R.drawable.gray_shapes);
            ivFundamental.setImageResource(R.mipmap.tingyuanyin);
            if (mSPUtils.getBoolean(Configuration.USERSHARE, false)){
                ivListenRecord.setImageResource(R.mipmap.tingyuanyin);
            }else {
                ivListenRecord.setImageResource(R.mipmap.tingluyin);
            }
            totalPage = mfUserImgRecordListBeanList.size();
            List<GrindingEarsBean> mGrindingEarsList = new ArrayList<>();
            for (int i = 0; i < mfUserImgRecordListBeanList.size(); i++) {
                View view = LayoutInflater.from(CommentActivity.this).inflate(R.layout.layout_advertisement, null);
                ImageView imageView = view.findViewById(R.id.iv_image);
                Glide.with(getApplicationContext()).load(mfUserImgRecordListBeanList.get(i).getAddress()).into(imageView);
                GrindingEarsBean grindingEarsBean = new GrindingEarsBean();//把播放地址传过去
                GrindingEarsBean.MfAudioBean mfAudioBean = new GrindingEarsBean.MfAudioBean();
                mfAudioBean.setAddress(mfUserImgRecordListBeanList.get(i).getAudio());
                grindingEarsBean.setMfAudio(mfAudioBean);
                mGrindingEarsList.add(grindingEarsBean);
                viewContains.add(view);
            }
            myPagerAdapter.notifyDataSetChanged();
            mCommentRecordService = new CommentRecordService(mGrindingEarsList, mContext);
            mCommentRecordService.songNum = currentPosition;
            if (!mSPUtils.getBoolean(Configuration.USERSHARE, false)){
                mCommentRecordService.play();
                setProgressBar(currentPosition);
                vpInfo.setCurrentItem(currentPosition);
            }else {
                setProgressBar(0);
                vpInfo.setCurrentItem(0);
            }

            if (null != dialog && dialog.isShow()) {
                dialog.cancel();
            }

        } else if (null != mLocalList && mLocalList.size() > 0) {
            if (currentPosition >= mLocalList.size()){
                currentPosition = 0;
            }
            isRecording = false;
            llListenRecord.setEnabled(false);
            llListenRecord.setBackgroundResource(R.drawable.gray_shapes);
            ivFundamental.setImageResource(R.mipmap.tingluyin);
            ivListenRecord.setImageResource(R.mipmap.tingyuanyin);
            totalPage = mLocalList.size();
            for (int i = 0; i < mLocalList.size(); i++) {
                View view = LayoutInflater.from(CommentActivity.this).inflate(R.layout.layout_advertisement, null);
                ImageView imageView = view.findViewById(R.id.iv_image);
                Glide.with(getApplicationContext()).load(mLocalList.get(i).getImageUrl()).into(imageView);
                viewContains.add(view);
            }
            myPagerAdapter.notifyDataSetChanged();
            setProgressBar(currentPosition);
            MoreFunApplication.isOut = false;//这里是进入
            Intent intent = new Intent();
            intent.setAction("GETMUSICPOSITION");
            intent.setPackage("com.mf.morefun"); //指定启动的是那个应用（lq.cn.twoapp）中的Action(b.aidl.DownLoadService)指向的服务组件
            startService(intent);
            mHomeWorkOriginalService = new HomeWorkOriginalService(mLocalList.get(0).getLocalListenUrl());
            mHomeWorkOriginalService.play();
            vpInfo.setCurrentItem(currentPosition);

            if (null != dialog && dialog.isShow()) {
                dialog.cancel();
            }

        } else {
            ToastUtils.show(getApplicationContext(), "暂无数据", 100);
        }
    }

    private void setProgressBar(int currentPosition) {
        int index = (100 / totalPage);
        if (currentPosition == (totalPage - 1)) {
            pbSpeed.setProgress(100);
        } else {
            pbSpeed.setProgress(index * (currentPosition + 1));
        }
    }

    private void setPagerListener() {
        vpInfo.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (isRecording) {
                    currentPosition = position;
                    setProgressBar(currentPosition);//更新进度条
                    if (null != mCommentRecordService) {
                        mCommentRecordService.songNum = currentPosition;
                        if (isCanPlay){
                            mCommentRecordService.play();
                            ivListenRecord.setImageResource(R.mipmap.tingluyin);
                        }
                    }
                } else {
                    if (null != mHomeWorkOriginalService && null != mHomeWorkOriginalService.player && mLocalViewList.size() > 0) {
                        setProgressBar(position);//更新进度条
                        int mPosition = 0;
                        if (position == 0) {
                            mPosition = position;
                        } else {
                            mPosition = position - 1;
                        }
                        if (position == 0) {
                            mHomeWorkOriginalService.player.seekTo(0);
                        } else {
                            mHomeWorkOriginalService.player.seekTo((int) (mLocalViewList.get(mPosition).getVodStart() * 1000));
                        }
                        if (isCanPlay){
                            mHomeWorkOriginalService.goPlay();
                        }
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    public void onRecorderFinish(int status, String path) {

    }

    private class MyPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return viewContains.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//                ((ViewPager) container).removeView(viewContains.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            position %= viewContains.size();
            if (position < 0) {
                position = viewContains.size() + position;
            }
            View view = viewContains.get(position);
            // 如果View已经在之前添加到了一个父组件，则必须先remove，否则会抛出IllegalStateException。
            ViewParent vp = view.getParent();
            if (vp != null) {
                ViewGroup parent = (ViewGroup) vp;
                parent.removeView(view);
            }
            container.addView(view);
            return view;
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }
    }


    private void setPagerAdapter() {
        myPagerAdapter = new MyPagerAdapter();
        vpInfo.setAdapter(myPagerAdapter);
    }

    private boolean isSuccess = false;

    private void showCicleImg(String headImg) {
        CircleCrop circleCrop = new CircleCrop();
        RequestOptions options = RequestOptions.bitmapTransform(circleCrop);
        Glide.with(CommentActivity.this).asBitmap().load(headImg).listener(new mRequestListener(ivHead)).apply(options).into(new TransformationCommitUtils(ivHead, CommentActivity.this));
    }

    @Override
    protected void initData() {

    }

    private class mRequestListener implements RequestListener {
        private ImageView ivPersonhead;

        public mRequestListener(ImageView ivPersonhead) {
            this.ivPersonhead = ivPersonhead;
        }

        @Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
            Log.d(TAG, "onException: " + e.toString() + "  model:" + model + " isFirstResource: " + isFirstResource);
            Message msg = new Message();
            msg.what = 100;
            msg.obj = ivPersonhead;
            mHandler.sendMessage(msg);
            return false;
        }

        @Override
        public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
            Log.e(TAG, "model:" + model + " isFirstResource: " + isFirstResource);
            return false;
        }
    }

    ;

    private boolean isOriginal = false;
    private boolean isRecord = false;
    private boolean isRecording = true;

    @OnClick({R.id.iv_back, R.id.ll_sendflower, R.id.iv_luyin, R.id.iv_voicetype,R.id.tv_cancel, R.id.tv_sure, R.id.ll_text, R.id.ll_voicecomment, R.id.ll_listen, R.id.ll_listen_fundamental, R.id.ll_listen_record, R.id.ll_share, R.id.ll_right, R.id.voice_recond_play, R.id.voice_recond_type})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                mSPUtils.putBoolean(Configuration.USERSHARE, false);
                finish();
                break;
            case R.id.ll_sendflower://送花
                try {
                    if( ! MoreFunApplication.loginBean.getResult().getUserType().equals("1") )
                    {
                        showSendFlower();
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            case R.id.iv_luyin://语音点评里面点击录音
                if (type.equals("1")) {
                    ivVoicetype.setVisibility(View.GONE);
                    if (null != mCommentRecordService && null != mCommentRecordService.player && mCommentRecordService.player.isPlaying()) {
                        mCommentRecordService.stop();
                    }
                    if (null != mHomeWorkOriginalService && null != mHomeWorkOriginalService.player && mHomeWorkOriginalService.player.isPlaying()) {
                        mHomeWorkOriginalService.pause();
                    }
                    llListenRecord.setBackgroundResource(R.drawable.blue_shapes);
                    llListenRecord.setEnabled(true);
                    ivListenRecord.setImageResource(R.mipmap.tingyuanyin);
                    llListenFundamental.setBackgroundResource(R.drawable.blue_shapes);
                    llListenFundamental.setEnabled(true);
                    ivFundamental.setImageResource(R.mipmap.tingyuanyin);
                    if (ivRecordShow.getVisibility() == View.VISIBLE) {

                        stopRecord();

                        ivRecordShow.setVisibility(View.GONE);

                        voiceRecondPlay.setVisibility(View.VISIBLE);

                        if (null != animationDrawablePlay) {
                            animationDrawablePlay.start();
                        }

                        ivVoicetype.setVisibility(View.GONE);

                        playInModeStream();

                    } else {
                        ivRecordShow.setVisibility(View.VISIBLE);
                        ivRecordShow.getDrawable().setLevel(0);
                        voiceRecondPlay.setVisibility(View.GONE);
                        if (null != animationDrawablePlay) {
                            animationDrawablePlay.stop();
                        }
                        stopPlay();
                        ivVoicetype.setVisibility(View.GONE);
                        startRecord();
                    }
                }
                break;
            case R.id.iv_voicetype://语音点评里面点击播放


                if (isHaveRecord()) {//老师就做本地录音

                    voiceRecondPlay.setVisibility(View.VISIBLE);

                    if (null != animationDrawablePlay) {
                        animationDrawablePlay.start();
                    }

                    ivVoicetype.setVisibility(View.GONE);

                    playInModeStream();
                }
                break;
            case R.id.tv_cancel://语音点评
                rlVoice.setVisibility(View.GONE);
                llComment.setVisibility(View.VISIBLE);
                ivVoicetype.setVisibility(View.VISIBLE);
                ivRecordShow.setVisibility(View.GONE);
                voiceRecondPlay.setVisibility(View.GONE);
                if (null != animationDrawablePlay) {
                    animationDrawablePlay.stop();
                }
                stopPlay();
                stopRecord();
                break;
            case R.id.tv_sure://语音点评  提交录音文件
                rlVoice.setVisibility(View.GONE);
                llComment.setVisibility(View.VISIBLE);
                ivRecordShow.setVisibility(View.GONE);
                ivVoicetype.setVisibility(View.VISIBLE);
                voiceRecondPlay.setVisibility(View.GONE);
                if (null != animationDrawablePlay) {
                    animationDrawablePlay.stop();
                }
                if (type.equals("1")) {
                    stopPlay();
                    stopRecord();
                    if (isHaveRecord()) {

                        if (null != dialog && !dialog.isShow()) {
                            dialog.show();
                        }

                        UploadUtil uploadUtil = new UploadUtil();
                        uploadUtil.uploadFile(CommentActivity.this,
                                mSPUtils.getString(Configuration.ACCESSKEYID),
                                mSPUtils.getString(Configuration.ACCESSKEYSECRET),
                                mSPUtils.getString(Configuration.SECURITYTOKEN),
                                mSPUtils.getString(Configuration.ENDPOINT),
                                mSPUtils.getString(Configuration.BUCKETNAME),
                                recordName + "record.mp3",
                                getBasePath() + "/" + recordName + "record.mp3", true);
                    }
                }
                break;
            case R.id.ll_text://文字点评
                if (type.equals("1")) {
                    llText.setBackgroundResource(R.mipmap.mineselected);
                    llVoicecomment.setBackgroundResource(R.mipmap.noselect);
                    llListen.setBackgroundResource(R.mipmap.noselect);
                    llRe.setBackgroundResource(R.mipmap.noselect);
                    tvText.setTextColor(getResources().getColor(R.color.white));
                    tvVoicecomment.setTextColor(0xff666666);
                    tvListen.setTextColor(0xff666666);
                    tvRe.setTextColor(0xff666666);
                    ivText.setImageResource(R.mipmap.homeworktextselected);
                    ivVoicecomment.setImageResource(R.mipmap.homeworkvoice);
                    ivListen.setImageResource(R.mipmap.homeworklisten);
                    ivRe.setImageResource(R.mipmap.homeworkre);
                    voiceRecondType.setVisibility(View.INVISIBLE);
                    //判别一下是否有点评
                    if (MoreFunApplication.loginBean.getResult().getUserType().equals("1")) {
                        if (null != mfTpComment && !StringUtils.isEmpty(mfTpComment.getTeacherTextComment())) {
                            showTextComment();
                        } else {
                            ToastUtils.show(getApplicationContext(), "暂无文字点评", 100);
                        }
                    } else {
                        showTextComment();
                    }
                }
                break;
            case R.id.ll_voicecomment://语音点评
                if (type.equals("1")) {
                    if (null != mCommentRecordService && null != mCommentRecordService.player && mCommentRecordService.player.isPlaying()) {
                        mCommentRecordService.stop();
                    }
                    if (null != mHomeWorkOriginalService && null != mHomeWorkOriginalService.player && mHomeWorkOriginalService.player.isPlaying()) {
                        mHomeWorkOriginalService.pause();
                    }
                    llListenRecord.setBackgroundResource(R.drawable.blue_shapes);
                    llListenRecord.setEnabled(true);
                    ivListenRecord.setImageResource(R.mipmap.tingyuanyin);
                    llListenFundamental.setBackgroundResource(R.drawable.blue_shapes);
                    llListenFundamental.setEnabled(true);
                    ivFundamental.setImageResource(R.mipmap.tingyuanyin);
                    llText.setBackgroundResource(R.mipmap.noselect);
                    llVoicecomment.setBackgroundResource(R.mipmap.mineselected);
                    llListen.setBackgroundResource(R.mipmap.noselect);
                    llRe.setBackgroundResource(R.mipmap.noselect);
                    tvText.setTextColor(0xff666666);
                    tvVoicecomment.setTextColor(getResources().getColor(R.color.white));
                    tvListen.setTextColor(0xff666666);
                    tvRe.setTextColor(0xff666666);
                    ivText.setImageResource(R.mipmap.homeworktext);
                    ivVoicecomment.setImageResource(R.mipmap.homeworkvoiceselected);
                    ivListen.setImageResource(R.mipmap.homeworklisten);
                    ivRe.setImageResource(R.mipmap.homeworkre);
                    rlVoice.setVisibility(View.VISIBLE);
                    llComment.setVisibility(View.GONE);
                    voiceRecondType.setVisibility(View.INVISIBLE);
                    if (null != animationDrawableType) {
                        animationDrawableType.stop();
                    }
                }
                break;
            case R.id.ll_listen://收听点评
                if (type.equals("1")) {
                    llText.setBackgroundResource(R.mipmap.noselect);
                    llVoicecomment.setBackgroundResource(R.mipmap.noselect);
                    llListen.setBackgroundResource(R.mipmap.mineselected);
                    llRe.setBackgroundResource(R.mipmap.noselect);
                    if (null != mCommentRecordService && null != mCommentRecordService.player && mCommentRecordService.player.isPlaying()) {
                        mCommentRecordService.pause();
                    }
                    if (null != mHomeWorkOriginalService && null != mHomeWorkOriginalService.player && mHomeWorkOriginalService.player.isPlaying()) {
                        mHomeWorkOriginalService.pause();
                    }
                    tvText.setTextColor(0xff666666);
                    tvVoicecomment.setTextColor(0xff666666);
                    tvListen.setTextColor(getResources().getColor(R.color.white));
                    tvRe.setTextColor(0xff666666);
                    ivText.setImageResource(R.mipmap.homeworktext);
                    ivVoicecomment.setImageResource(R.mipmap.homeworkvoice);
                    ivListen.setImageResource(R.mipmap.homeworklistenselected);
                    ivRe.setImageResource(R.mipmap.homeworkre);
                    if (MoreFunApplication.loginBean.getResult().getUserType().equals("1")) {//学员旧查看点评
                        if (null != mfTpComment && !StringUtils.isEmpty(mfTpComment.getTeacherVoiceComment())) {
                            voiceRecondType.setVisibility(View.VISIBLE);
                            if (null != animationDrawableType) {
                                animationDrawableType.start();
                            }
                            musicCommentService = new MusicCommentService(mfTpComment.getTeacherVoiceComment(), CommentActivity.this);
                            musicCommentService.play();
                        } else {
                            voiceRecondType.setVisibility(View.INVISIBLE);
                            if (null != animationDrawableType) {
                                animationDrawableType.stop();
                            }
                            ToastUtils.show(getApplicationContext(), "暂无语音点评", 100);
                        }
                    } else {
                        if (isHaveRecord()) {//老师就做本地录音
                            voiceRecondType.setVisibility(View.VISIBLE);
                            if (null != animationDrawableType) {
                                animationDrawableType.start();
                            }
                            playInModeStream();
                        }
                        else if(null != mfTpComment && !StringUtils.isEmpty(mfTpComment.getTeacherVoiceComment())) {
                            voiceRecondType.setVisibility(View.VISIBLE);
                            if (null != animationDrawableType) {
                                animationDrawableType.start();
                            }
                            musicCommentService = new MusicCommentService(mfTpComment.getTeacherVoiceComment(), CommentActivity.this);
                            musicCommentService.play();
                        }
                        else {
                            voiceRecondType.setVisibility(View.INVISIBLE);
                            if (null != animationDrawableType) {
                                animationDrawableType.stop();
                            }
                            ToastUtils.show(getApplicationContext(), "暂无录音", 100);
                        }
                    }
                }
                break;
            case R.id.ll_listen_fundamental://听原音
                isOriginal = true;
                if (null != mCommentRecordService && null != mCommentRecordService.player) {//把之前的销毁
                    mCommentRecordService.stop();
                }
                if (null != mLocalViewList && mLocalViewList.size() > 0){
                    ivFundamental.setImageResource(R.mipmap.tingluyin);
                    ivListenRecord.setImageResource(R.mipmap.tingyuanyin);
                }
                if (null != mHomeWorkOriginalService && null != mHomeWorkOriginalService.player) {
                    if (isRecord) {
                        isCanPlay = true;
                        if (null != mLocalViewList && mLocalViewList.size() > 0) {
                            showViewPager(null, mLocalViewList);
                        }
                    } else {
                        if (mHomeWorkOriginalService.player.isPlaying()) {
                            mHomeWorkOriginalService.pause();
                            llListenRecord.setEnabled(true);
                            llListenRecord.setBackgroundResource(R.drawable.blue_shapes);
                            ivFundamental.setImageResource(R.mipmap.tingyuanyin);
                        } else {
                            isCanPlay = true;
                            if (null != mLocalViewList && mLocalViewList.size() > 0) {
                                if (currentPosition == (mLocalViewList.size() - 1)) {
                                    currentPosition = 0;
                                    vpInfo.setCurrentItem(currentPosition);
                                } else {
                                    mHomeWorkOriginalService.goPlay();
                                }
                                llListenRecord.setEnabled(false);
                                llListenRecord.setBackgroundResource(R.drawable.gray_shapes);
                                ivFundamental.setImageResource(R.mipmap.tingluyin);
                            }
                        }
                    }
                } else {
                    if (!StringUtils.isEmpty(bookId)) {
                        isCanPlay = true;
                        llListenRecord.setEnabled(false);
                        llListenRecord.setBackgroundResource(R.drawable.gray_shapes);
                        initListenOriginal();
                    }
                }
                isRecord = false;
                break;
            case R.id.ll_listen_record://听录音
                if (null != mRecordList && mRecordList.size() > 0){
                    ivFundamental.setImageResource(R.mipmap.tingyuanyin);
                    ivListenRecord.setImageResource(R.mipmap.tingluyin);
                    isRecord = true;
                }
                if (null != mHomeWorkOriginalService && null != mHomeWorkOriginalService.player) {
                    mHomeWorkOriginalService.stop();
                }
                if (null != mCommentRecordService && null != mCommentRecordService.player) {
                    if (isOriginal) {//点了原音那么我们就重新加载一次
                        isCanPlay = true;
                        if (null != mRecordList && mRecordList.size() > 0) {
                            showViewPager(mRecordList, null);
                        }
                    } else {
                        if (mCommentRecordService.player.isPlaying()) {
                            mCommentRecordService.stop();
                            llListenFundamental.setEnabled(true);
                            llListenFundamental.setBackgroundResource(R.drawable.blue_shapes);
                            ivListenRecord.setImageResource(R.mipmap.tingyuanyin);
                        } else {
                            isCanPlay = true;
                            //如果没有在播放点评，点评过程中不播放录音
                            if ( null == musicCommentService || ( null != musicCommentService.player && !musicCommentService.player.isPlaying() )){
                                mCommentRecordService.play();
                            }


                            llListenFundamental.setEnabled(false);
                            llListenFundamental.setBackgroundResource(R.drawable.gray_shapes);
                            ivListenRecord.setImageResource(R.mipmap.tingluyin);
                        }
                    }
                } else {
                    isCanPlay = true;
                    showViewPager(mRecordList, null);
                }
                isOriginal = false;
                break;
            case R.id.ll_share://分享
                mSPUtils.putBoolean(Configuration.USERSHARE, true);
                initShareHttp();
                isCanPlay = false;
                //把所有音频文件
                if (null != mCommentRecordService && null != mCommentRecordService.player && mCommentRecordService.player.isPlaying()) {//把之前的销毁
                    mCommentRecordService.stop();
                }
                if (null != mHomeWorkOriginalService && null != mHomeWorkOriginalService.player && mHomeWorkOriginalService.player.isPlaying()) {
                    mHomeWorkOriginalService.pause();
                }
                llListenFundamental.setEnabled(true);
                llListenFundamental.setBackgroundResource(R.drawable.blue_shapes);
                llListenRecord.setEnabled(true);
                llListenRecord.setBackgroundResource(R.drawable.blue_shapes);
                ivFundamental.setImageResource(R.mipmap.tingyuanyin);
                ivListenRecord.setImageResource(R.mipmap.tingyuanyin);
                break;
            case R.id.ll_right:
                if (llLeft.getVisibility() == View.VISIBLE) {
                    ScaleAnimation scaleAnimation = new ScaleAnimation(
                            1.0f, 1.25f, 1.0f, 1.0f,
                            Animation.RELATIVE_TO_SELF, 1.0f,
                            Animation.RELATIVE_TO_SELF, 0.5f);
                    scaleAnimation.setDuration(1000);//动画持续时间
                    llRight.startAnimation(scaleAnimation);//设置给控件
                    TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                            Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF,
                            0.0f, Animation.RELATIVE_TO_SELF, 0.0f);
                    mHiddenAction.setDuration(1000);
                    llLeft.startAnimation(mHiddenAction);
                    mHiddenAction.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            llLeft.setVisibility(View.GONE);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                } else {
                    ScaleAnimation scaleAnimation = new ScaleAnimation(
                            1.0f, 0.75f, 1.0f, 1.0f,
                            Animation.RELATIVE_TO_SELF, 1.0f,
                            Animation.RELATIVE_TO_SELF, 0.5f);
                    scaleAnimation.setDuration(1000);//动画持续时间
                    llRight.startAnimation(scaleAnimation);//设置给控件
                    TranslateAnimation mShowAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                            -1.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                            0.0f);
                    mShowAction.setDuration(1000);
                    llLeft.startAnimation(mShowAction);
                    mShowAction.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            llLeft.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                }
                break;
            case R.id.voice_recond_play:
                stopPlay();
                break;
            case R.id.voice_recond_type:
                stopPlay();
                break;
        }
    }

    private boolean isHaveRecord() {
        File file = new File(getBasePath() + "/" + recordName + "record.mp3");
        if (file.exists()) {
            return true;
        } else {
            return false;
        }
    }

    private void initListenOriginal() {
        if (null != dialog && !dialog.isShow()) {
            dialog.show();
        }
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.LISTENORIHINAL);
        RequestAchievementBean requestAchievementBean = new RequestAchievementBean();
        requestAchievementBean.setId(bookId);
        params.setBodyContent(JSON.toJSONString(requestAchievementBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())) {
                            ListenOriginalBean listenOriginalBean = JSON.parseObject(resultBean.getResult(), ListenOriginalBean.class);
                            if (!StringUtils.isEmpty(listenOriginalBean.getImgList()) && !StringUtils.isEmpty(listenOriginalBean.getImgAudioRelList())) {
                                List<MfimgListBean> mfimgListBeanList = JSON.parseArray(listenOriginalBean.getImgList(), MfimgListBean.class);
                                List<MfPicaudioRelListBean> mfPicaudioRelListBeanList = JSON.parseArray(listenOriginalBean.getImgAudioRelList(), MfPicaudioRelListBean.class);
                                //两个集合必须都不为空
                                if (null != mfimgListBeanList && mfimgListBeanList.size() > 0 && null != mfPicaudioRelListBeanList && mfPicaudioRelListBeanList.size() > 0) {
                                    //必须等于  因为一对一
                                    if (mfimgListBeanList.size() == mfPicaudioRelListBeanList.size()) {
                                        //组装成自己的对象
                                        List<LocalListenBean> mLocalList = new ArrayList<>();
                                        for (int i = 0; i < mfimgListBeanList.size(); i++) {
                                            LocalListenBean localListenBean = new LocalListenBean();
                                            localListenBean.setImageUrl(mfimgListBeanList.get(i).getAddress());
                                            localListenBean.setLocalListenUrl("");
                                            if (null != listenOriginalBean.getAudioList()){
                                                localListenBean.setNetListenUrl(listenOriginalBean.getAudioList().get(0).getAddress());
                                            }
                                            localListenBean.setVodStart(mfPicaudioRelListBeanList.get(i).getVodStart());
                                            localListenBean.setMusicName(bookName);
                                            localListenBean.setId(0);
                                            mLocalList.add(localListenBean);
                                        }
                                        //先判断是否要去下载 本地有了就不需要下载
                                        showLocalList(mLocalList);
                                    }
                                }
                            } else {
                            }
                        } else {
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (null != dialog && dialog.isShow()) {
                    dialog.cancel();
                }
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void showLocalList(List<LocalListenBean> mLocalList) {
        try {
            List<LocalListenBean> localList = manager.selector(LocalListenBean.class).where("netListenUrl", "==", mLocalList.get(0).getNetListenUrl()).findAll();
            if (null != localList && localList.size() > 0) {
                manager.delete(localList);
                removeDuplicate(localList);
                List<LocalListenBean> mNeedList = new ArrayList<>();
                for (int i = 0; i < localList.size(); i++) {
                    manager.save(localList.get(i));
                    if (mLocalList.get(0).getNetListenUrl().equals(localList.get(i).getNetListenUrl())) {
                        mNeedList.add(localList.get(i));//拿到存在本地的
                    }
                }
                if (null != mNeedList && mNeedList.size() > 0) {
                    //这里拿到集合可以直接播放
                    ablePlay(mNeedList);
                } else {
                    //这里需要去下载
                    needDownload(mLocalList);
                }
            } else {
                //这里肯定是要去下载
                needDownload(mLocalList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void removeDuplicate(List<LocalListenBean> localMessageList) {
        List<LocalListenBean> newList = new  ArrayList<LocalListenBean>();
        for(LocalListenBean msg : localMessageList){
            if (newList.size() > 0){
                if (!isSure(newList, msg.getImageUrl())){
                    newList.add(msg);
                }
            }else {
                newList.add(msg);
            }
        }
        localMessageList.clear();
        localMessageList.addAll(newList);
    }

    private boolean isSure(List<LocalListenBean> newList, String imageUrl) {
        boolean isHave = false;
        for (LocalListenBean newMsg : newList){
            if (newMsg.getImageUrl().equals(imageUrl)){
                isHave = true;
            }
        }
        return isHave;
    }

    //需要去下载的集合
    private void needDownload(List<LocalListenBean> mLocalList) {
        DownloadUtils.getsInstance().setListener(new DownloadUtils.OnDownloadListener() {
            @Override
            public void onDowload(String mp3Url) {
                //把本地地址加上 存进入数据库
                insertDb(mp3Url, mLocalList);
                ablePlay(mLocalList);
            }

            @Override
            public void onFailed(String error) {
                ToastUtils.show(getApplicationContext(), "下载失败", 100);
            }
        }).download(mLocalList.get(0));
    }

    private void insertDb(String mp3Url, List<LocalListenBean> mLocalList) {
        try {
            for (int i = 0; i < mLocalList.size(); i++) {
                mLocalList.get(i).setLocalListenUrl(mp3Url);
                manager.save(mLocalList.get(i));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //能够播放的集合   但是还要调整集合顺序
    private void ablePlay(List<LocalListenBean> mNeedList) {
        //先初始化一个集合  排序
        getVodStartList(mNeedList, mLocalViewList);
        //同时还要展示viewpager
        showViewPager(null, mLocalViewList);
    }

    private void getVodStartList(List<LocalListenBean> mNeedList, List<LocalListenBean> mLocalList) {
        double mVodArray[] = new double[mNeedList.size()];
        for (int i = 0; i < mNeedList.size(); i++) {
            mVodArray[i] = mNeedList.get(i).getVodStart();
        }
        //冒泡排序一下
        bubbleSort(mVodArray);
        for (int i = 0; i < mVodArray.length; i++) {
            //取到对象
            getNeedBean(mVodArray[i], mNeedList, mLocalList);
        }
    }

    private void getNeedBean(double vod, List<LocalListenBean> mNeedList, List<LocalListenBean> mLocalList) {
        for (int i = 0; i < mNeedList.size(); i++) {
            if (vod == mNeedList.get(i).getVodStart()) {
                mLocalList.add(mNeedList.get(i));
            }
        }
    }

    private void bubbleSort(double[] mVodArray) {
        for (int i = 0; i < mVodArray.length - 1; i++) {
            for (int j = 0; j < mVodArray.length - 1 - i; j++) {
                if (mVodArray[j] > mVodArray[j + 1]) {
                    double temp;
                    temp = mVodArray[j];
                    mVodArray[j] = mVodArray[j + 1];
                    mVodArray[j + 1] = temp;
                }
            }
        }
    }


    private void initShareHttp() {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.SHARE);
        RequestShareBean requestShareBean = new RequestShareBean();
        requestShareBean.setUserID(mSPUtils.getString(Configuration.USERID));
        requestShareBean.setContextID(contextId);
        requestShareBean.setContextType(contextType);
        requestShareBean.setShareType("2");//1为图片  2为链接
        requestShareBean.setMediaType(mediaType);
        params.setBodyContent(JSON.toJSONString(requestShareBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d(result);
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())) {
                            ShareBean shareBean = JSON.parseObject(resultBean.getResult(), ShareBean.class);
                            try {
                                showSharePop(shareBean);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
                
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private PopupWindow sharePop;

    private void showSharePop(ShareBean shareBean) {
        closePop();
        if (sharePop == null) {
            LayoutInflater inflater = getLayoutInflater();
            View view = inflater.inflate(R.layout.layout_sharepop, null);
            // 这里启动头像
            RelativeLayout rl_bg = (RelativeLayout) view.findViewById(R.id.rl_bg);
            rl_bg.getBackground().setAlpha(100);
            TextView tv_cancel = view.findViewById(R.id.tv_cancel);
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    closePop();
                    
                }
            });
            LinearLayout ll_pengyou = view.findViewById(R.id.ll_pengyouquan);
            ll_pengyou.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    closePop();
                    if (checkInstalled(0)) {
                        showShare(0, shareBean);
                    } else {
                        ToastUtils.show(CommentActivity.this, "请先安装微信", 100);
                    }
                }
            });
            LinearLayout ll_wechat = view.findViewById(R.id.ll_wechat);
            ll_wechat.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    closePop();
                    if (checkInstalled(0)) {
                        showShare(1, shareBean);
                    } else {
                        ToastUtils.show(CommentActivity.this, "请先安装微信", 100);
                    }
                }
            });
            LinearLayout ll_wechatcollect = view.findViewById(R.id.ll_wechatcollect);
            ll_wechatcollect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    closePop();
                    if (checkInstalled(0)) {
                        showShare(2, shareBean);
                    } else {
                        ToastUtils.show(CommentActivity.this, "请先安装微信", 100);
                    }
                }
            });
            int h = CommentActivity.this.getWindowManager().getDefaultDisplay().getHeight();
            sharePop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, h);
            sharePop.setFocusable(true);
            sharePop.setOutsideTouchable(true);
            sharePop.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // 这里如果返回true的话，touch事件将被拦截
                    // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                    return false;
                }
            });
            sharePop.setBackgroundDrawable(new BitmapDrawable());
            Rect rect = new Rect();
            CommentActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
            int winHeight = CommentActivity.this.getWindow().getDecorView().getHeight();
            sharePop.showAtLocation(CommentActivity.this.getWindow().getDecorView(), Gravity.BOTTOM, 0, winHeight - rect.bottom);
        }
    }

    private boolean checkInstalled(int index) {
        boolean isInstall = false;
        switch (index) {
            case 0://微信
                isInstall = isInstallWx("com.tencent.mm");
                break;
            case 1://QQ
                isInstall = isInstallWx("com.tencent.mobileqq");
                break;
        }
        return isInstall;
    }

    /**
     * 是否安装微信
     */
    public boolean isInstallWx(String packageNames) {
        try {
            PackageManager manager = CommentActivity.this.getPackageManager();
            List<PackageInfo> list = manager.getInstalledPackages(0);
            List<String> mList = new ArrayList<String>();
            if (null != list && list.size() != 0) {
                for (int i = 0; i < list.size(); i++) {
                    mList.add(list.get(i).packageName);
                }
            }
            if (null != mList && mList.size() != 0) {
                return mList.contains(packageNames);
            } else {
                return false;
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return false;
    }

    private void showShare(int index, ShareBean shareBean) {
        if (null != shareBean) {
            UMImage image = new UMImage(CommentActivity.this, shareBean.getCover());//资源文件
            String shareUrl = shareBean.getLinkAddress();
            UMWeb web = new UMWeb(shareUrl);
            web.setTitle(shareBean.getContext());//标题
            web.setThumb(image);  //缩略图
            web.setDescription(shareBean.getName());//描述
            switch (index) {
                case 0://朋友群
                    new ShareAction(CommentActivity.this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                            .withMedia(web).setCallback(shareListener)
                            .share();
                    break;
                case 1://微信
                    new ShareAction(CommentActivity.this).setPlatform(SHARE_MEDIA.WEIXIN)
                            .withMedia(web).setCallback(shareListener)
                            .share();
                    break;
                case 2://微信收藏
                    new ShareAction(CommentActivity.this).setPlatform(SHARE_MEDIA.WEIXIN_FAVORITE)
                            .withMedia(web).setCallback(shareListener)
                            .share();
                    break;
            }
        }
    }

    private void closePop() {
        if (null != sharePop) {
            sharePop.dismiss();
            sharePop = null;
        }
        if (null != mFlowPop) {
            mFlowPop.dismiss();
            mFlowPop = null;
        }
        if (null != mTextPop) {
            mTextPop.dismiss();
            mTextPop = null;
        }
    }

    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(CommentActivity.this, "分享成功", Toast.LENGTH_LONG).show();
            
            String reward = "1";
            if (type.equals("0")) {
                reward = "1";
            } else {
                reward = "2";
            }
            mSendStartOrFlowerNet = new SendStarOrFlowerNet(CommentActivity.this, lyContent);
            mSendStartOrFlowerNet.initGetFlower(10
                    , mSPUtils.getString(Configuration.USERID),
                    bookId,
                    "2", reward
            );
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            
            Toast.makeText(CommentActivity.this, "分享失败" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            
            Toast.makeText(CommentActivity.this, "取消分享", Toast.LENGTH_LONG).show();
        }
    };
    private PopupWindow mTextPop;
    private int score = 20;
    private String textComment = "";
    private String teacherVoiceComment = "";

    //文字点评
    private void showTextComment() {
        try {
            closePop();
            if (mTextPop == null) {
                LayoutInflater inflater = getLayoutInflater();
                View view = inflater.inflate(R.layout.layout_poptext, null);
                RelativeLayout rl_bg = view.findViewById(R.id.rl_bg);
                rl_bg.getBackground().setAlpha(100);
                TextView tv_score = view.findViewById(R.id.tv_score);
                tv_score.setText(mSPUtils.getString(Configuration.SCORE) + "分");
                score = Integer.parseInt(mSPUtils.getString(Configuration.SCORE));
                EditText edit_score = view.findViewById(R.id.edit_score);
                RatingBar ratingBar = view.findViewById(R.id.ratingBar);
                if (null != mfTpComment && mfTpComment.getUserCommentStar() != 0){
                    try {
                        tv_score.setText(mfTpComment.getUserCommentStar() + "分");
                        score = mfTpComment.getUserCommentStar();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else {
                    tv_score.setText("20分");
                    score = 20;
                }
                ratingBar.setRating((score / 20f));
                mSPUtils.putString(Configuration.SCORE, score + "");
                if (null != mfTpComment && !StringUtils.isEmpty(mfTpComment.getTeacherTextComment())){
                    edit_score.setText(mfTpComment.getTeacherTextComment());
                }
                if (MoreFunApplication.loginBean.getResult().getUserType().equals("1")) {
                    edit_score.setFocusable(false);
                    ratingBar.setEnabled(false);
                } else {
                    edit_score.setFocusable(true);
                    ratingBar.setEnabled(true);
                }
                ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
                    @Override
                    public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                        ratingBar.setRating(rating);
                        tv_score.setText(((int) (20 * rating)) + "分");
                        score = (int) (20 * rating);
                        mSPUtils.putString(Configuration.SCORE, score + "");
                    }
                });
                TextView tv_cancel = view.findViewById(R.id.tv_cancel);
                tv_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        closePop();
                    }
                });
                TextView tv_sure = view.findViewById(R.id.tv_sure);
                tv_sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        closePop();
                        if (!StringUtils.isEmpty(edit_score.getText().toString())) {
                            textComment = edit_score.getText().toString();
                            mSPUtils.putString(Configuration.TEXTCOMMENT, textComment);
                            if (!MoreFunApplication.loginBean.getResult().getUserType().equals("1")) {
                                initSaveComment();
                            }
                        }
                    }
                });
                int h = CommentActivity.this.getWindowManager().getDefaultDisplay().getHeight();
                mTextPop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, h);
                mTextPop.setFocusable(true);
                mTextPop.setOutsideTouchable(true);
                mTextPop.setTouchInterceptor(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        // 这里如果返回true的话，touch事件将被拦截
                        // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                        return false;
                    }
                });
                mTextPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        closePop();
                    }
                });
                mTextPop.setBackgroundDrawable(new BitmapDrawable());
                Rect rect = new Rect();
                CommentActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
                int winHeight = CommentActivity.this.getWindow().getDecorView().getHeight();
                mTextPop.showAtLocation(CommentActivity.this.getWindow().getDecorView(), Gravity.CENTER, 0, winHeight);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void initSaveComment() {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.HOMEWORKCOMMENTSAVE);
        RequestHomeWorkSaveBean requestHomeWorkSaveBean = new RequestHomeWorkSaveBean();
        requestHomeWorkSaveBean.setType(type);
        if (StringUtils.isEmpty(mSPUtils.getString(Configuration.TEXTCOMMENT))) {
            textComment = "";
        } else {
            textComment = mSPUtils.getString(Configuration.TEXTCOMMENT);
        }
        requestHomeWorkSaveBean.setTeacherTextComment(textComment);
        if (StringUtils.isEmpty(mSPUtils.getString(Configuration.TEACHERVOICECOMMENT))) {
            teacherVoiceComment = "";
        } else {
            teacherVoiceComment = mSPUtils.getString(Configuration.TEACHERVOICECOMMENT);
        }
        requestHomeWorkSaveBean.setTeacherVoiceComment(teacherVoiceComment);
        if (StringUtils.isEmpty(mSPUtils.getString(Configuration.SCORE))) {
            score = 20;
        } else {
            score = Integer.parseInt(mSPUtils.getString(Configuration.SCORE));
        }
        requestHomeWorkSaveBean.setUserCommentStar(score);
        RequestHomeWorkSaveBean.BookBean bookBean = new RequestHomeWorkSaveBean.BookBean();
        if (StringUtils.isEmpty(bookId)) {
            bookBean.setId("");
        } else {
            bookBean.setId(bookId);
        }
        requestHomeWorkSaveBean.setBook(bookBean);
        RequestHomeWorkSaveBean.CommentUserBean commentUserBean = new RequestHomeWorkSaveBean.CommentUserBean();
        commentUserBean.setId(userId);
        requestHomeWorkSaveBean.setCommentUser(commentUserBean);
        RequestHomeWorkSaveBean.CommentTeacherBean commentTeacherBean = new RequestHomeWorkSaveBean.CommentTeacherBean();
        if (IsLoginBean.isNo(true)) {
            if (MoreFunApplication.loginBean.getResult().getUserType().equals("1")) {
                commentTeacherBean.setId(getIntent().getStringExtra("STUDENT"));
            } else {
                commentTeacherBean.setId(mSPUtils.getString(Configuration.USERID));
            }
        } else {
            commentTeacherBean.setId(mSPUtils.getString(Configuration.USERID));
        }
        requestHomeWorkSaveBean.setCommentTeacher(commentTeacherBean);
        RequestHomeWorkSaveBean.TpRecordBean tpRecordBean = new RequestHomeWorkSaveBean.TpRecordBean();
        tpRecordBean.setId(mfRecordId);
        RequestHomeWorkSaveBean.WorkBean workBean = new RequestHomeWorkSaveBean.WorkBean();
        requestHomeWorkSaveBean.setTpRecord(tpRecordBean);
        requestHomeWorkSaveBean.setWork(workBean);
        params.setBodyContent(JSON.toJSONString(requestHomeWorkSaveBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                if (null != dialog && dialog.isShow()) {
                    dialog.cancel();
                }

                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() != 0) {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }else {
                        if (null != mfTpComment){
                            mfTpComment.setTeacherTextComment(mSPUtils.getString(Configuration.TEXTCOMMENT));
                            mfTpComment.setTeacherVoiceComment(mSPUtils.getString(Configuration.TEACHERVOICECOMMENT));
                            mfTpComment.setUserCommentStar(score);
                        }else {
                            mfTpComment = new MfTpComment();
                            mfTpComment.setTeacherTextComment(mSPUtils.getString(Configuration.TEXTCOMMENT));
                            mfTpComment.setTeacherVoiceComment(mSPUtils.getString(Configuration.TEACHERVOICECOMMENT));
                            mfTpComment.setUserCommentStar(score);
                        }
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private PopupWindow mFlowPop;
    private int flower = 5;

    //送花
    private void showSendFlower() {
        closePop();
        if (mFlowPop == null) {
            LayoutInflater inflater = getLayoutInflater();
            View view = inflater.inflate(R.layout.layout_flowerpop, null);
            RelativeLayout rl_bg = view.findViewById(R.id.rl_bg);
            rl_bg.getBackground().setAlpha(100);
            TextView tv_cancel = view.findViewById(R.id.tv_cancel);
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    closePop();
                }
            });
            TextView tv_sure = view.findViewById(R.id.tv_sure);
            tv_sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {//奖励记录保存
                    closePop();
                    initSendFlower();
                }
            });
            LinearLayout ll_five = view.findViewById(R.id.ll_five);
            ImageView iv_five = view.findViewById(R.id.iv_five);
            TextView tv_five = view.findViewById(R.id.tv_five);
            LinearLayout ll_ten = view.findViewById(R.id.ll_ten);
            ImageView iv_ten = view.findViewById(R.id.iv_ten);
            TextView tv_ten = view.findViewById(R.id.tv_ten);
            LinearLayout ll_twenty = view.findViewById(R.id.ll_twenty);
            ImageView iv_twenty = view.findViewById(R.id.iv_twenty);
            TextView tv_twenty = view.findViewById(R.id.tv_twenty);
            showFlower(iv_five, tv_five, iv_ten, tv_ten, iv_twenty, tv_twenty, flower);
            ll_five.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    flower = 5;
                    showFlower(iv_five, tv_five, iv_ten, tv_ten, iv_twenty, tv_twenty, flower);
                }
            });
            ll_ten.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    flower = 10;
                    showFlower(iv_five, tv_five, iv_ten, tv_ten, iv_twenty, tv_twenty, flower);
                }
            });
            ll_twenty.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    flower = 20;
                    showFlower(iv_five, tv_five, iv_ten, tv_ten, iv_twenty, tv_twenty, flower);
                }
            });
            int h = CommentActivity.this.getWindowManager().getDefaultDisplay().getHeight();
            mFlowPop = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, h);
            mFlowPop.setFocusable(true);
            mFlowPop.setOutsideTouchable(true);
            mFlowPop.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // 这里如果返回true的话，touch事件将被拦截
                    // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                    return false;
                }
            });
            mFlowPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    closePop();
                }
            });
            mFlowPop.setBackgroundDrawable(new BitmapDrawable());
            Rect rect = new Rect();
            CommentActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
            int winHeight = CommentActivity.this.getWindow().getDecorView().getHeight();
            mFlowPop.showAtLocation(CommentActivity.this.getWindow().getDecorView(), Gravity.CENTER, 0, winHeight - rect.bottom);
        }
    }

    private void initSendFlower() {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.SENDFLOWER);
        RequestSendFlowerBean requestSendFlowerBean = new RequestSendFlowerBean();
        requestSendFlowerBean.setFromType("11");
        requestSendFlowerBean.setRewardType("2");
        requestSendFlowerBean.setRewardNumber(flower + "");
        requestSendFlowerBean.setWorkHomeworkType("2");
        RequestSendFlowerBean.TeacherBean teacherBean = new RequestSendFlowerBean.TeacherBean();
        teacherBean.setId(mSPUtils.getString(Configuration.USERID));
        requestSendFlowerBean.setTeacher(teacherBean);
        RequestSendFlowerBean.StudentBean studentBean = new RequestSendFlowerBean.StudentBean();
        studentBean.setId(getIntent().getStringExtra("STUDENT"));
        requestSendFlowerBean.setStudent(studentBean);
        RequestSendFlowerBean.HomeworkIdBean homeworkIdBean = new RequestSendFlowerBean.HomeworkIdBean();
        homeworkIdBean.setId(contextId);
        requestSendFlowerBean.setHomeworkId(homeworkIdBean);
        params.setBodyContent(JSON.toJSONString(requestSendFlowerBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() != 0) {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }else {
                        tvFlower.setText(flower + "");
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void showFlower(ImageView iv_five, TextView tv_five, ImageView iv_ten, TextView tv_ten, ImageView iv_twenty, TextView tv_twenty, int flower) {
        switch (flower) {
            case 5://展示ui
                iv_five.setImageResource(R.mipmap.mine_flower_icon);
                iv_ten.setImageResource(R.mipmap.flower);
                iv_twenty.setImageResource(R.mipmap.flower);
                break;
            case 10:
                iv_five.setImageResource(R.mipmap.flower);
                iv_ten.setImageResource(R.mipmap.mine_flower_icon);
                iv_twenty.setImageResource(R.mipmap.flower);
                break;
            case 20:
                iv_five.setImageResource(R.mipmap.flower);
                iv_ten.setImageResource(R.mipmap.flower);
                iv_twenty.setImageResource(R.mipmap.mine_flower_icon);
                break;
        }
    }

    private int count;

    //开始录音
    public void startRecord() {
        try {
            final File file = new File(getBasePath() + "/" + recordName + "record.mp3");
            if (!file.mkdirs()) {
                Log.e("record", "Directory not created");
            }
            if (file.exists()) {
                file.delete();
            }
            LameMp3Manager.instance.startRecorder(getBasePath() + "/" + recordName + "record.mp3");
            LameMp3Manager.instance.setMediaRecorderListener(this);
            count = 4000;
            mHandler.sendEmptyMessageDelayed(0, 100);
        }catch (Exception e){
            e.printStackTrace();
            showMissingPermissionDialog();
        }
    }

    // 显示缺失权限提示
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(CommentActivity.this);
        builder.setTitle(R.string.help);
        builder.setMessage(R.string.string_help_text);

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.quit, new DialogInterface.OnClickListener() {
            @Override public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        builder.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
            @Override public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
                startAppSettings();
            }
        });
        builder.show();
    }

    // 启动应用的设置
    private void startAppSettings() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(localIntent);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (mHandler.hasMessages(0)) {
                mHandler.removeMessages(0);
            }
            switch (msg.what) {
                case 0:
                    if (count == 10000) {
                        count = 4000;
                    } else {
                        count = count + 500;
                    }
                    mHandler.sendEmptyMessageDelayed(0, 100);
                    ivRecordShow.getDrawable().setLevel(count);
                    break;
                case 1:
                    stopPlay();
                    break;
                case 100:
                    CircleCrop circleCrop = new CircleCrop();
                    RequestOptions options = RequestOptions.bitmapTransform(circleCrop);
                    Glide.with(CommentActivity.this).asBitmap().load(R.mipmap.home_me).apply(options).into(new TransformationCommitUtils((ImageView) msg.obj, CommentActivity.this));
                    break;
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(CommentActivity.this);
                    errorPop.showPop("");
                    break;
            }
        }
    };


    public String getBasePath() {
        String strPath = null;
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            strPath = getApplicationContext().getFilesDir() + "/" + "lameMp3";
        } else {
            strPath = Environment.getExternalStorageDirectory() + "/" + "lameMp3";
        }
        File dir = new File(strPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return strPath;
    }

    //结束录音
    public void stopRecord() {
        ivVoicetype.setVisibility(View.VISIBLE);
        ivRecordShow.setVisibility(View.GONE);
        LameMp3Manager.instance.stopRecorder();
    }

    /**
     * 播放，使用stream模式 + File.separator
     */
    private void playInModeStream() {
        MediaPlayUtil.init(getApplicationContext());
        MediaPlayUtil.playSound(getBasePath() + "/" + recordName + "record.mp3", new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                stopPlay();
            }
        });
    }

    /**
     * 停止播放
     */
    private void stopPlay() {
        if (null != animationDrawableType) {
            animationDrawableType.stop();
        }
        if (null != animationDrawablePlay) {
            animationDrawablePlay.stop();
        }
        if (null != musicCommentService) {
            musicCommentService.stop();
        }
        voiceRecondPlay.setVisibility(View.GONE);
        voiceRecondType.setVisibility(View.INVISIBLE);
        ivVoicetype.setVisibility(View.VISIBLE);

        MediaPlayUtil.release();
    }


}
